package com.book.publishing.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.business.entity.BookIndent;
import com.book.business.service.BookIndentService;
import com.book.publishing.entity.BookMessage;
import com.book.buyout.entity.Prelisting;
import com.book.publishing.service.BookMessageService;
import com.book.buyout.service.PrelistingService;
import com.book.common.annotation.ControllerEndpoint;
import com.book.common.annotation.Log;
import com.book.common.controller.BaseController;
import com.book.common.entity.FebsConstant;
import com.book.common.entity.FebsResponse;
import com.book.common.entity.QueryRequest;
import com.book.common.utils.BookEveryId;
import com.book.common.utils.FebsUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * @Author: 孙鑫
 * @Description: 20173952
 */

@Controller
public class BookMessageController extends BaseController {
    @Autowired
    BookMessageService bookMessageService;
    @Autowired
    PrelistingService prelistingService;
    @Autowired
    BookIndentService bookIndentService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "publishing/bookMessage")
    public String bookMessageIndex() {
        return FebsUtil.view("publishing/bookMessage/bookMessageList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "publishing/bookMessage/add")
    public String bookMessageAdd() {
        return FebsUtil.view("publishing/bookMessage/bookMessageAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "publishing/bookMessage/update/{id}")
    public String bookMessageUpdate(@PathVariable Integer id, ModelMap modelMap) {
        BookMessage bookMessage = this.bookMessageService.getById(id);
        modelMap.put("bookMessage", bookMessage);
        return FebsUtil.view("publishing/bookMessage/bookMessageUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "publishing/bookMessage/ask/{id}")
    public String bookMessageAsk(@PathVariable Integer id, ModelMap modelMap) {
        BookMessage bookMessage = this.bookMessageService.getById(id);
        modelMap.put("bookMessage", bookMessage);
        return FebsUtil.view("publishing/bookMessage/bookMessageAsk");
    }

    @GetMapping("bookMessage")
    @ResponseBody
    @RequiresPermissions("bookMessage:view")
    public FebsResponse getAllType(BookMessage bookMessage) {
        return new FebsResponse().success().data(this.bookMessageService.findBookMessage(bookMessage));
    }

    @GetMapping("bookMessage/dlist")
    @ResponseBody
    @RequiresPermissions("bookMessage:view")
    public FebsResponse bookMessageList() {
        return new FebsResponse().success().data(this.bookMessageService.getAllType());
    }

    @Log("访问书籍信息")
    @GetMapping("bookMessage/list")
    @ResponseBody
    @RequiresPermissions("bookMessage:view")
    public FebsResponse bookMessageIPage(QueryRequest request, BookMessage bookMessage) {
        Map<String, Object> dataTable = getDataTable(this.bookMessageService.pageBookMessage(request, bookMessage));
        return new FebsResponse().success().data(dataTable);
    }

    @Log("书籍-新增")
    @PostMapping("bookMessage")
    @ResponseBody
    @RequiresPermissions("bookMessage:add")
    @ControllerEndpoint(operation = "新增书籍信息成功", exceptionMessage = "新增书籍信息失败")
    public FebsResponse bookMessageAdd(BookMessage bookMessage) {
        BookMessage one = bookMessageService.getOne(new QueryWrapper<BookMessage>().lambda().eq(BookMessage::getBookname, bookMessage.getBookname()));
        if (one == null) {
            this.bookMessageService.addBookMessage(bookMessage);
        } else {
            return new FebsResponse().message("该书籍已经存在！");
        }
        return new FebsResponse().success();
    }

    @Log("书籍-修改")
    @PostMapping("bookMessage/update")
    @ResponseBody
    @RequiresPermissions("bookMessage:update")
    @ControllerEndpoint(operation = "修改书籍信息成功", exceptionMessage = "修改书籍信息失败")
    public FebsResponse bookMessageUpdate(BookMessage bookMessage) {
        BookMessage one = bookMessageService.getOne(new QueryWrapper<BookMessage>().lambda().eq(BookMessage::getBookname, bookMessage.getBookname()));
        one.setBookmoney(bookMessage.getBookmoney());
        this.bookMessageService.updateBookMessage(one);
        return new FebsResponse().success();
    }

    @Log("书籍-删除")
    @PostMapping("bookMessage/delete/{ids}")
    @ResponseBody
    @RequiresPermissions("bookMessage:delete")
    @ControllerEndpoint(operation = "删除书籍信息成功", exceptionMessage = "删除书籍信息失败")
    public FebsResponse bookMessagedelete(@PathVariable String ids) {
        String[] attr = ids.split(",");
        List<BookMessage> bookMessageList = this.bookMessageService.askBookMessage(attr);
        for (int i = 0; i < bookMessageList.size(); i++) {
            List<Prelisting> list = prelistingService.list(new QueryWrapper<Prelisting>().lambda().notIn(Prelisting::getStatus, "1"));
            if (list.size() > 0) {
                return new FebsResponse().message("该书籍准备采购，不能修改！");
            }
        }
        bookMessageService.deleteBookMessage(attr);
        return new FebsResponse().success();
    }

    @Log("书籍-申请采购")
    @PostMapping("bookMessage/askone")
    @ResponseBody
    @RequiresPermissions("bookMessage:ask")
    @ControllerEndpoint(operation = "申请采购信息添加成功", exceptionMessage = "添加采购信息失败")
    public FebsResponse bookMessageone(@Valid BookMessage bookMessage) {
        if (bookMessage.getNum() < 0) {
            return new FebsResponse().message("您添加的采购信息有误！");
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance();
        String yearAndMonths = format.format(calendar.getTime());
        String[] yearAndMonth = yearAndMonths.split("-");
        Prelisting prelisting = prelistingService.getOne(new QueryWrapper<Prelisting>().lambda()
                .eq(Prelisting::getStatus, BookEveryId.BOOK_EXECUTE_NO)
                .eq(Prelisting::getFlag, BookEveryId.BOOK_PERMIT_NO)
                .eq(Prelisting::getBookname, bookMessage.getBookname()));
        if (prelisting == null) {
            prelisting = new Prelisting()
                    .setBookname(bookMessage.getBookname())
                    .setBookmoney(bookMessage.getBookmoney())
                    .setType(bookMessage.getType())
                    .setOmit("1")
                    .setYear(yearAndMonth[0])
                    .setMonth(yearAndMonth[1])
                    .setTotalmoney(bookMessage.getBookmoney() * bookMessage.getNum())
                    .setFlag(BookEveryId.BOOK_PERMIT_NO)
                    .setStatus(BookEveryId.BOOK_EXECUTE_NO);
            prelisting.setNumber(bookMessage.getNum());
            prelistingService.addPrelisting(prelisting);
            return new FebsResponse().success();
        } else {
            prelisting.setNumber(prelisting.getNumber() + bookMessage.getNum());
            prelistingService.updatePrelisting(prelisting);
            return new FebsResponse().success();
        }
    }

    @Log("书籍-申请采购")
    @PostMapping("bookMessage/ask/{ids}")
    @ResponseBody
    @RequiresPermissions("bookMessage:ask")
    @ControllerEndpoint(operation = "申请采购信息添加成功", exceptionMessage = "添加采购信息失败")
    public FebsResponse bookMessageask(@PathVariable String ids) {
        String[] attr = ids.split(",");
        List<BookMessage> bookMessageList = bookMessageService.askBookMessage(attr);
        for (int i = 0; i < bookMessageList.size(); i++) {
            QueryWrapper<Prelisting> prelistingQueryWrapper = new QueryWrapper<>();
            //这里不用确定预购单是否存在逻辑删除数据，前面已经定义
            prelistingQueryWrapper.eq("status", BookEveryId.BOOK_EXECUTE_NO);
            prelistingQueryWrapper.eq("flag", BookEveryId.BOOK_PERMIT_NO);
            prelistingQueryWrapper.eq("bookname", bookMessageList.get(i).getBookname());
            Prelisting prelisting = prelistingService.getOne(prelistingQueryWrapper);
            if (prelisting == null) {
                prelisting = new Prelisting()
                        .setBookname(bookMessageList.get(i).getBookname())
                        .setBookmoney(bookMessageList.get(i).getBookmoney())
                        .setType(bookMessageList.get(i).getType())
                        .setTotalmoney(bookMessageList.get(i).getBookmoney() * 100)
                        .setNumber(100)
                        .setFlag(BookEveryId.BOOK_PERMIT_NO)
                        .setStatus(BookEveryId.BOOK_EXECUTE_NO);
                prelistingService.addPrelisting(prelisting);
            } else {
                prelisting.setNumber(prelisting.getNumber() + 100);
                prelistingService.updatePrelisting(prelisting);
            }
        }
        return new FebsResponse().success();
    }
}

